<template>
    <a-modal
      v-model:visible="visible"
      :title="title"
      :mask-closable="false"
      :esc-to-close="false"
      :width="width >= 600 ? 600 : '100%'"
      draggable
      @before-ok="save"
      @close="reset"
    >
      <GiForm ref="formRef" v-model="form" :columns="columns" />
    </a-modal>
  </template>
  
  <script setup lang="ts">
  import { Message } from '@arco-design/web-vue'
  import { useWindowSize } from '@vueuse/core'
  import { getConsumableTracks, addConsumableTracks, updateConsumableTracks } from '@/apis/asset/consumable/tracks'

  import {  consumableInbound } from '@/apis/asset/consumable/records'

  import { type ColumnItem, GiForm } from '@/components/GiForm'
  import { useResetReactive } from '@/hooks'
  import { useDict } from '@/hooks/app'
  import { consumables } from '@/hooks/asset'

  const emit = defineEmits<{
    (e: 'save-success'): void
  }>()
  
  const { width } = useWindowSize()
  const visible = ref(false)

  const title = computed(() => ('耗材入库'))
  const formRef = ref<InstanceType<typeof GiForm>>()
  
  const { consumableList, getConsumableList } = consumables()

  const [form, resetForm] = useResetReactive({
    // todo 待补充
  })
  
  const columns: ColumnItem[] = reactive([
    {
      label: '耗材',
      field: 'consumableId',
      type: 'select', 
      span: 24,
      required: true,
      props: {
        options: consumableList,
        placeholder: "请选择耗材",
        allowClear: true,
        allowSearch: true,
      }
    },
   
    {
      label: '入库数量',
      field: 'changeNum',
      type: 'input-number', 
      span: 24,
      rules: [{ required: true, message: '请输入入库数量' }]
    },
    {
      label: '购买日期',
      field: 'purchasedDate',
      type: 'date-picker',
      span: 24,
      rules: [{ required: true, message: '请输入购买日期' }]
    },
    {
      label: '过保日期',
      field: 'expiredDate',
      type: 'date-picker',
      span: 24,
      rules: [{ required: true, message: '请输入过保日期' }]
    },
    {
      label: '描述',
      field: 'description',
      type: 'textarea',
      props: {
        maxLength: 250
      },
      span: 24,
    },
   
  ])
  
  // 重置
  const reset = () => {
    formRef.value?.formRef?.resetFields()
    resetForm()
  }
  
  // 保存
  const save = async () => {
    try {
      const isInvalid = await formRef.value?.formRef?.validate()
      console.log(form)
      await consumableInbound(form)
      Message.success('入库成功')
      emit('save-success')
      return true
    } catch (error) {
      return false
    }
  }
  
  // 入库
  const onAdd = async () => {
    reset()
    visible.value = true
    if (!consumableList.value.length) {
      await getConsumableList()
    }
  }

  defineExpose({ onAdd })
  </script>
  
  <style scoped lang="scss"></style>
  